<template>
  <div class="login-container">
    <img class="logo" src="@/assets/logo.svg" />
    <h2>登录</h2>
    <el-form :model="form" @submit.prevent="handleLogin" label-width="70px">
      <el-form-item label="用户名">
        <el-input v-model="form.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" show-password placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label-width="0px">
        <el-checkbox v-model="form.rememberPassword">记住密码</el-checkbox>
      </el-form-item>
      <el-button type="primary" native-type="submit" :loading="loading" :disabled="!form.userName || !form.password">{{
        loading ? '登录中...' : '登录' }}</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { loginAPI } from '@/api/userLogin' // 导入API接口
import { SysUser } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const form = reactive({ userName: '', password: '', rememberPassword: false })

// 页面加载时检查本地存储的记住密码信息
onMounted(() => {
  const savedLoginInfo = localStorage.getItem('savedLoginInfo')
  if (savedLoginInfo) {
    try {
      const { userName, password, rememberPassword } = JSON.parse(savedLoginInfo)
      form.userName = userName
      form.password = password
      form.rememberPassword = rememberPassword
    } catch (error) {
      console.error('解析保存的登录信息失败:', error)
      // 清除无效的存储数据
      localStorage.removeItem('savedLoginInfo')
    }
  }
})

const handleLogin = async () => {
  // 表单验证
  if (!form.userName.trim() || !form.password.trim()) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  loading.value = true

  try {
    // 调用真实的登录接口
    const response: any = await loginAPI({
      userName: form.userName,
      password: form.password,
    })

    console.log('登录响应:', response)

    // 根据接口文档，响应结构为: { code, message, result }
    const { code, message, result } = response

    if (code === 200) {
      // 处理记住密码逻辑
      if (form.rememberPassword) {
        const loginInfo = {
          userName: form.userName,
          password: form.password, // 注意：实际项目中建议加密存储
          rememberPassword: true,
        }
        localStorage.setItem('savedLoginInfo', JSON.stringify(loginInfo))
      } else {
        localStorage.removeItem('savedLoginInfo')
      }

      // 根据实际返回的用户信息构建 userInfo
      // 注意：接口文档中返回的是 result 对象（SysUser）
      // 需要根据实际的 SysUser 结构来调整
      const token = result.token || result.id // 临时方案，需要确认
      const userInfo: SysUser = {
        id: result.id,
        userName: result.userName,
        nickname: result.nickname,
        phone: result.phone,
        gender: result.gender,
        state: result.state,
      }

      userStore.login(token, userInfo)
      localStorage.setItem('token', token)

      ElMessage.success(message || '登录成功')
      router.push('/dashboard')
    } else {
      ElMessage.error(message || '登录失败')
    }
  } catch (error: unknown) {
    console.error('登录错误详情:', error)
    // 根据后端返回的错误信息显示
    ElMessage.error(error!.toString())
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding-top: 200px;
}

.logo {
  width: 50px;
  height: 50px;
}

h2 {
  margin-bottom: 20px;
}

button {
  width: 100%;
}
</style>
